package redis.session ;

import java.io.Serializable ;
import java.util.HashMap ;
import java.util.Map ;
import java.util.concurrent.TimeUnit ;

import javax.annotation.Resource ;

import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
import org.springframework.data.redis.core.RedisTemplate ;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer ;
import org.springframework.stereotype.Component ;

import redis.RedisConfig ;

/**
 * 实现从redis读写session存储
 * @author 80002165 @date 2017年7月5日 上午9:12:07
 */
@Component
public class SessionService {
    static Logger logger = LoggerFactory.getLogger(SessionService.class) ;
    
    private JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer() ;
    
    @Resource
    private RedisTemplate<Serializable, Serializable> redisTemplate ;
    
    @SuppressWarnings("unchecked")
    public Map<String, Object> getSession(String sid) {
        Map<String, Object> session = new HashMap<String, Object>() ;
        Object obj = redisTemplate.opsForValue().get(RedisConfig.SESSION_DISTRIBUTED_SESSIONID + sid) ;
        if (obj != null) {
            // 对取出的数据做处理
            obj = jdkSerializer.deserialize((byte[]) obj) ;
            session = (Map<String, Object>) obj ;
            return session ;
        }
        
        return session ;
    }
    
    public void saveSession(String sid, Map<String, Object> session) {
        try {
            redisTemplate.opsForValue().set(RedisConfig.SESSION_DISTRIBUTED_SESSIONID + sid, jdkSerializer.serialize(session), RedisConfig.SESSION_DISTRIBUTED_TIMEOUT, TimeUnit.DAYS) ;
        } catch (Exception e) {
            logger.error("保存分布式session，{}出错", sid, e) ;
        }
    }
}
